package com.crocodileQ.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.crocodileQ.common.AppException;
import com.crocodileQ.common.R;
import com.crocodileQ.domain.VO.BlogUserLoginVO;
import com.crocodileQ.domain.VO.UserInfoVO;
import com.crocodileQ.domain.entity.LoginUser;
import com.crocodileQ.domain.entity.User;
import com.crocodileQ.enums.AppExceptionMsgEnum;
import com.crocodileQ.service.BlogLoginService;
import com.crocodileQ.utils.BeanCopyUtil;
import com.crocodileQ.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 用户登录
     * @param user
     * @return
     */
    public R<BlogUserLoginVO> login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (BeanUtil.isEmpty(authenticate)){
            throw new AppException(AppExceptionMsgEnum.REQUIRED_USERNAME);
        }


        //生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJwt(userId);

        //todo redis 缓存loginUser
        //token 和 userInfo封装
        UserInfoVO userInfoVO = BeanCopyUtil.copyBean(loginUser.getUser(), UserInfoVO.class);
        BlogUserLoginVO blogUserLoginVO = new BlogUserLoginVO(token, userInfoVO);


        return R.success(blogUserLoginVO);
    }

    /**
     * 用户退出登录
     * @return
     */
    public R logout() {
        //todo redis删除用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        SecurityContextHolder.clearContext();


        return R.success("退出登录成功");
    }
}
